import {Button, message, Pagination, Space, Table, Tooltip} from "antd";
import {useEffect, useState} from "react";
import RoleSearch from "../../../components/console/role/roleSearch";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import {EditOutlined, EyeOutlined, PlusCircleOutlined, RedoOutlined} from "@ant-design/icons";
import RoleCreate from "../../../components/console/role/roleCreate";
import {useNavigate} from "react-router-dom";

/**
 * 角色管理页面
 *
 * @returns {JSX.Element}
 * @constructor
 */
const ConsoleRolePage = () => {

    const navigate = useNavigate();
    const [messageApi, contextHolder] = message.useMessage();

    // 分页部分请求参数
    const [paginationReq, setPaginationReq] = useState({
        pageNum: 1,
        pageSize: 10
    });

    // 查询系统角色请求参数
    const [pageSysRoleReq, setPageSysRoleReq] = useState({
        // 角色名
        roleName: '',
        // 角色描述
        roleDescription: ''
    })


    // 分页查询系统角色结果
    const [pageSysRoleResp, setPageSysRoleResp] = useState({
        total: 0,
        pageCount: 1,
        records: []
    })

    // 创建角色模态框打开状态
    const [createRoleModalVisible, setCreateRoleModalVisible] = useState(false);

    // 定义分页列表字段
    const pageSysRoleRespFields = [
        {
            title: "序号",
            key: "index",
            width: 80,
            align: 'center',
            render: (text, record, index) => {
                return (
                    <div style={{
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        color: '#666',
                        fontWeight: 500
                    }}>
                        {(paginationReq.pageNum - 1) * paginationReq.pageSize + index + 1}
                    </div>
                )
            },
            isShow: true
        }, {
            title: "id",
            dataIndex: 'id',
            key: 'id',
            align: 'center',
            isShow: false
        }, {
            title: "角色名",
            dataIndex: 'roleName',
            key: 'roleName',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#1890ff',
                    fontWeight: 500
                }}>{text}</div>
            )
        }, {
            title: "角色描述",
            dataIndex: 'roleDescription',
            key: 'roleDescription',
            align: 'center',
            isShow: true,
            render: (text) => (
                // 用Tooltip包裹，添加宽度限制和省略号样式
                <Tooltip title={text || '无描述'} placement="top">
                    <div style={{
                        color: '#ff007f',
                        fontWeight: 500,
                        maxWidth: 200, // 限制宽度（可根据需求调整）
                        whiteSpace: 'nowrap', // 不换行
                        overflow: 'hidden', // 超出隐藏
                        textOverflow: 'ellipsis' // 显示省略号
                    }}>
                        {text || '无描述'}
                    </div>
                </Tooltip>
            )
        }, {
            title: "已关联用户数",
            dataIndex: 'relationUserCount',
            key: 'relationUserCount',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#009900',
                    fontWeight: 500
                }}>{text}</div>
            )
        }, {
            title: "已分配权限数量",
            dataIndex: 'relationPermissionCount',
            key: 'relationPermissionCount',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#ff6600',
                    fontWeight: 500
                }}>{text}</div>
            )
        }, {
            title: '创建时间',
            dataIndex: 'createdTime',
            key: 'createdTime',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#006666',
                    fontSize: '12px'
                }}>{text}</div>
            )
        }, {
            title: '创建人',
            dataIndex: 'createdByUserNickname',
            key: 'createdByUserNickname',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#009999'
                }}>{text}</div>
            )
        }, {
            title: '最后编辑时间',
            dataIndex: 'lastModifiedTime',
            key: 'lastModifiedTime',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#004c99',
                    fontSize: '12px'
                }}>{text}</div>
            )
        }, {
            title: '最后编辑人',
            dataIndex: 'lastModifiedByUserNickname',
            key: 'lastModifiedByUserNickname',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#004c99'
                }}>{text}</div>
            )
        }, {
            title: '操作',
            align: 'center',
            render: (text, record) => (
                <Space size="small">
                    <Button
                        size={"small"}
                        type="text"
                        icon={<EyeOutlined/>}
                        style={{
                            fontSize: '14px',
                            color: '#1890ff',
                            backgroundColor: 'rgba(24, 144, 255, 0.05)',
                            border: '1px solid #91d5ff',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                        onMouseEnter={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.1)';
                            e.target.style.transform = 'translateY(-2px)';
                            e.target.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.05)';
                            e.target.style.transform = 'translateY(0)';
                            e.target.style.boxShadow = 'none';
                        }}
                        onClick={() => redirect2RoleDetail('search', record.id)}
                    >
                        查看
                    </Button>
                    <Button
                        size={"small"}
                        type="text"
                        icon={<EditOutlined/>}
                        style={{
                            fontSize: '14px',
                            color: '#fa8c16',
                            backgroundColor: 'rgba(250, 140, 22, 0.05)',
                            border: '1px solid #ffbb96',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                        onMouseEnter={(e) => {
                            e.target.style.backgroundColor = 'rgba(250, 140, 22, 0.1)';
                            e.target.style.transform = 'translateY(-2px)';
                            e.target.style.boxShadow = '0 2px 8px rgba(250, 140, 22, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.target.style.backgroundColor = 'rgba(250, 140, 22, 0.05)';
                            e.target.style.transform = 'translateY(0)';
                            e.target.style.boxShadow = 'none';
                        }}
                        onClick={() => redirect2RoleDetail('edit', record.id)}
                    >
                        编辑
                    </Button>
                </Space>
            ),
            isShow: true
        }
    ]

    /**
     * 分页查询系统用户
     */
    const pageQuerySysRole = () => {
        RequestUtils.post(RequestApis.roleManage.page, {
            ...paginationReq,
            ...pageSysRoleReq
        }).then(res => {
            setPageSysRoleResp(res.data.data);
        }).catch(err => messageApi.error(err.message))
    }

    /**
     * 重定向到角色详情页面
     */
    const redirect2RoleDetail = (type, id) => {
        navigate(`/console/role/${type}/${id}`);
    }

    /**
     * 刷新角色权限的缓存
     */
    const refreshRolePermissionCache = () => {
        RequestUtils.post(RequestApis.permissionManage.refreshRoleCache, {})
            .then(() => {
                messageApi.success("操作成功, 开始执行角色权限缓存刷新任务");
            }).catch(err => messageApi.error(err.message))
    }

    /**
     * 分页搜索条件变化后, 自动重新执行分页查询
     */
    useEffect(() => {
        pageQuerySysRole();
        // eslint-disable-next-line
    }, [paginationReq])

    // 表格行样式 - 交替行背景色
    const getRowClassName = (record, index) => {
        return index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
    };

    return (
        <div>
            {contextHolder}

            {/* 查询条件 */}
            <div style={{padding: '16px', paddingBottom: '8px'}}>
                <RoleSearch
                    setPaginationReq={setPaginationReq}
                    pageSysRoleReq={pageSysRoleReq}
                    setPageSysRoleReq={setPageSysRoleReq}
                    pageQuerySysRole={pageQuerySysRole}
                />
            </div>

            <div style={{marginBottom: '8px'}}>
                <Button
                    color={'purple'}
                    variant="solid"
                    style={{width: '180px'}}
                    onClick={() => setCreateRoleModalVisible(true)}
                >
                    <PlusCircleOutlined style={{marginRight: '8px'}}/>
                    新增角色
                </Button>

                <Button
                    color={'pink'}
                    variant="outlined"
                    style={{width: '220px', marginLeft: '16px'}}
                    onClick={() => refreshRolePermissionCache()}
                >
                    <RedoOutlined style={{marginRight: '8px'}}/>
                    刷新角色权限缓存
                </Button>
            </div>

            {/* 表格展示（表头固定，内容滚动） */}
            <div style={{
                backgroundColor: '#fff',
                borderRadius: '8px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.04)',
                overflow: 'hidden',
                transition: 'box-shadow 0.3s ease'
            }} onMouseOver={(e) => {
                e.currentTarget.style.boxShadow = '0 4px 16px rgba(0, 0, 0, 0.08)';
            }} onMouseOut={(e) => {
                e.currentTarget.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.04)';
            }}>
                <Table
                    dataSource={pageSysRoleResp.records}
                    columns={pageSysRoleRespFields.filter(item => item.isShow)}
                    pagination={false}
                    scroll={{
                        y: 'calc(100vh - 460px)',
                        x: 'max-content'
                    }}
                    bordered={false}
                    rowHoverable
                    style={{width: '100%'}}
                    tableLayout="fixed"
                    rowClassName={getRowClassName}
                    headerStyle={{
                        backgroundColor: '#fafafa',
                        color: '#1f2329',
                        fontWeight: 600,
                        fontSize: '14px',
                        borderBottom: '1px solid #e5e6eb',
                        padding: '12px 16px'
                    }}
                    bodyStyle={{
                        fontSize: '13px'
                    }}
                    rowStyle={{
                        height: '60px',
                        transition: 'background-color 0.2s ease'
                    }}
                    // 添加表格加载状态
                    loading={{
                        spinning: false, // 可以根据实际加载状态设置
                        indicator: <div style={{padding: '40px 0'}}>加载中...</div>
                    }}
                    // 表格行悬停样式
                    onRow={(record, index) => ({
                        onMouseEnter: (e) => {
                            e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.02)';
                        },
                        onMouseLeave: (e) => {
                            const isEven = index % 2 === 0;
                            e.currentTarget.style.backgroundColor = isEven ? '#fcfcfc' : '#fff';
                        },
                    })}
                />
            </div>

            {/* 分页组件 */}
            <div style={{
                display: "flex",
                justifyContent: "flex-end",
                alignItems: "center",
                height: '60px',
                marginTop: '16px',
                fontSize: '13px'
            }}>
                <Pagination
                    total={pageSysRoleResp.total}
                    current={paginationReq.pageNum}
                    pageSize={paginationReq.pageSize}
                    showSizeChanger
                    showQuickJumper
                    showTotal={(total) => {
                        return (
                            <div style={{fontSize: '15px'}}>
                                <span>共</span>
                                <span style={{color: 'red', fontWeight: 'bold'}}> {total} </span>
                                <span>条数据</span>
                            </div>
                        )
                    }}
                    pageSizeOptions={['10', '20', '50', '100', '200']}
                    onChange={(pageNum, pageSize) => {
                        setPaginationReq({
                            ...paginationReq,
                            pageNum: pageNum,
                            pageSize: pageSize
                        })
                    }}
                    onShowSizeChange={(current, size) => {
                        setPaginationReq({
                            ...paginationReq,
                            pageNum: current,
                            pageSize: size
                        })
                    }}
                    style={{
                        padding: '8px 16px'
                    }}
                    itemStyle={{
                        borderRadius: '4px',
                        margin: '0 2px',
                        transition: 'all 0.2s ease'
                    }}
                    prevIcon={<span style={{transition: 'transform 0.2s ease'}}>←</span>}
                    nextIcon={<span style={{transition: 'transform 0.2s ease'}}>→</span>}
                />
            </div>

            <RoleCreate
                messageApi={messageApi}
                visible={createRoleModalVisible}
                setVisible={setCreateRoleModalVisible}
                pageQuerySysRole={pageQuerySysRole}
            />

        </div>
    );
}

export default ConsoleRolePage;